package cn.edu.gzgs.controller;

import cn.edu.gzgs.dto.PageQueryDTO;
import cn.edu.gzgs.dto.UserDTO;
import cn.edu.gzgs.dto.UserRoleAssignDTO;
import cn.edu.gzgs.dto.UserStatusUpdateDTO;
import cn.edu.gzgs.service.UserService;
import cn.edu.gzgs.vo.ApiResponse;
import cn.edu.gzgs.vo.BatchOperationResultVO;
import cn.edu.gzgs.vo.ImportResultVO;
import cn.edu.gzgs.vo.UserVO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 教师管理Controller
 *
 * @author Zyf
 */
@RestController
@RequestMapping("/api/user")
@Tag(name = "教师管理接口")
@Slf4j
@PreAuthorize("hasAuthority('admin')")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/page")
    @Operation(summary = "分页查询教师列表")
    public ResponseEntity<ApiResponse<Page<UserVO>>> getUserPage(PageQueryDTO pageQueryDTO) {
        Page<UserVO> page = userService.getUserPage(pageQueryDTO);
        return ResponseEntity.ok(new ApiResponse<>(0, "查询成功", page));
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据ID获取教师详情")
    public ResponseEntity<ApiResponse<UserVO>> getUserById(@PathVariable Long id) {
        UserVO userVO = userService.getUserById(id);
        return ResponseEntity.ok(new ApiResponse<>(0, "查询成功", userVO));
    }

    @PostMapping
    @Operation(summary = "新增或更新教师")
    public ResponseEntity<ApiResponse<Long>> saveOrUpdateUser(@Valid @RequestBody UserDTO userDTO) {
        Long userId = userService.saveOrUpdateUser(userDTO);
        // 根据是否有ID判断是创建还是更新
        if (userDTO.getId() == null) {
            return ResponseEntity.status(HttpStatus.CREATED).body(new ApiResponse<>(0, "新增教师成功", userId));
        } else {
            return ResponseEntity.ok(new ApiResponse<>(0, "更新教师成功", userId));
        }
    }

    @PutMapping("/status")
    @Operation(summary = "批量修改教师状态")
    public ResponseEntity<ApiResponse<BatchOperationResultVO>> updateUserStatus(@Valid @RequestBody UserStatusUpdateDTO userStatusUpdateDTO) {
        BatchOperationResultVO result = userService.updateUserStatus(userStatusUpdateDTO);
        return ResponseEntity.ok(new ApiResponse<>(0, "状态修改成功", result));
    }

    @PostMapping("/roles/assign")
    @Operation(summary = "批量为用户分配角色")
    public ResponseEntity<ApiResponse<BatchOperationResultVO>> assignRolesToUsers(@Valid @RequestBody UserRoleAssignDTO userRoleAssignDTO) {
        BatchOperationResultVO result = userService.assignRolesToUsers(userRoleAssignDTO);
        return ResponseEntity.ok(new ApiResponse<>(0, "角色分配成功", result));
    }

    @PostMapping("/roles/unassign")
    @Operation(summary = "批量取消用户的角色")
    public ResponseEntity<ApiResponse<BatchOperationResultVO>> unassignRolesFromUsers(@Valid @RequestBody UserRoleAssignDTO userRoleAssignDTO) {
        BatchOperationResultVO result = userService.unassignRolesFromUsers(userRoleAssignDTO);
        return ResponseEntity.ok(new ApiResponse<>(0, "角色取消成功", result));
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "逻辑删除教师")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
        userService.deleteUserAndAssociations(id);
        return ResponseEntity.noContent().build();
    }

    @PreAuthorize("hasAuthority('file:upload') or hasAuthority('admin')")
    @PostMapping("/import")
    @Operation(summary = "上传文件(CSV/Excel)")
    public ResponseEntity<ApiResponse<ImportResultVO>> importRoster(@RequestParam("file") MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            // 这里可以保持，因为它是一个非常前置的、无需访问服务层的校验
            return ResponseEntity.badRequest().body(new ApiResponse<>(40001, "上传文件不能为空", null));
        }
        String originalFilename = file.getOriginalFilename();
        ImportResultVO result = userService.importRoster(file.getInputStream(), originalFilename);
        return ResponseEntity.status(HttpStatus.CREATED).body(new ApiResponse<>(0, "导入成功", result));
    }

    @GetMapping("/template")
    @Operation(summary = "下载文件导入模板")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        response.setContentType("text/csv");
        String fileName = URLEncoder.encode("教师花名册导入模板.csv", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName);

        String header = "序号,工号,姓名,最高学历,最高学位,高校系列职称名称,高校系列职称级别,非高校系列职称名称,非高校系列职称级别,现任职务,来校日期,所属教研室,备注,岗位\n";
        response.getOutputStream().write(header.getBytes(StandardCharsets.UTF_8));
    }
} 